(ns ura.data.Data
  (:require
   [toucan2.core :as t2]
   [cheshire.core :refer :all]
   [methodical.core :as m]
   [hikari-cp.core :refer :all]
   [next.jdbc :as jdbc]
   [next.jdbc.result-set :as rs]
   [next.jdbc.connection :as conns]
   [ura.config :as cfg]
   [taoensso.telemere :as t]
   [honey.sql :as hql]
   )
  (:use tupelo.core)
  )

;; init connection pool
(defn init-pool []
  (let [dbcfg cfg/dm
        poolcfg (:conn-pool cfg/cfg)
        conf (merge {
                     :driver-class-name (:classname dbcfg)
                     :jdbc-url (:jdbcUrl dbcfg)
                     :username (:user dbcfg)
                     :password (:password dbcfg)
                     }
                    poolcfg
                    )
        _ (t/log! {:data conf} "get pool config:")
        ]
   (defonce datasource (delay (make-datasource conf)))
    )
  )




;; (conns/->pool datasource)


(defn checkDataNull [value]
  (and
   (not (nil? value))
   (not (.equals "undefined" value))
   )
  )

(defn nextId [seqName]
  (->
   (jdbc/execute! cfg/dm [(str "select " seqName ".nextval")])
   first
   (:NEXTVAL)
   )
  )

(defn upcaseKey "update a map's key(keyword) to upper case"
  [m]
  (update-keys m #(-> % name clojure.string/upper-case keyword))
  )

(defn execute [sql]
  (spy sql)
  (jdbc/execute! @datasource sql {:builder-fn rs/as-unqualified-lower-maps})
  )

(defn executeSql [sqlData]
  (execute (hql/format sqlData))
  )
